package cas;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Date;
import java.util.TooManyListenersException;

import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

/**
 * @author Eri Setiawan
 * @version 1.0
 * @created 29-May-2011 10:33:05 AM
 */
public class Radio {

	private SerialPortHandler serial;
	Identity iden;
	public Radio(String portName) {
		super();
		iden = null;
		serial = new SerialPortHandler();
		try {
			serial.connect(portName, "Collision Avoidance System Radio", 9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, SerialPort.FLOWCONTROL_NONE);
			serial.serialPort.addEventListener(new SerialPortEventListener() {
				@Override
				public void serialEvent(SerialPortEvent evt) {
					if(evt.getEventType()==SerialPortEvent.DATA_AVAILABLE){
						try {
							iden = receive(1000);
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
			});
			serial.serialPort.notifyOnDataAvailable(true);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TooManyListenersException e) {
			e.printStackTrace();
		}
	}
	public Identity getReceivedIdentity(){
		return iden;
	}
	/**
	 * 
	 * @param waitingTime in millisecond
	 * @return
	 * @throws SQLException 
	 */
	public Identity receive(double waitingTime) throws SQLException{
		InputStream iStream = serial.getSerialInputStream();
		byte[] readBuffer = new byte[1024];
		String sentence = "";
		int len = 0;
		boolean isTimeup = false;
		double startTime = new Date().getTime();
		boolean isComplete = false;
		try {
			while(!isComplete && !isTimeup){
				isTimeup = !((new Date().getTime()-startTime)<=waitingTime);
				if ((len = iStream.read(readBuffer))>0&& !isTimeup) {
					sentence = sentence + new String(readBuffer,0,len);
					if(sentence.split(",").length==9&&
							sentence.contains("\n")&&sentence.contains("$")){
						isComplete = true;
					} else if(sentence.split(",").length>9){
						sentence = "";
					}
					isTimeup = !((new Date().getTime()-startTime)<=waitingTime);
				}
			}
			if(isTimeup){
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(sentence.equals(""))
			return null;
		return new Identity(sentence);
	}

	public void send(Identity identity) throws IOException{
		OutputStream oStream = serial.getSerialOutputStream();
		String s = identity.toString();
		byte[] b = new byte[s.length()];
		b = s.getBytes();
		try {
			oStream.write(b);	
			oStream.flush();
		} catch (IOException e) {
			System.err.println(e);
			throw new IOException(e);
		}
	}
	public SerialPort getSerialPort(){
		return serial.serialPort;
	}
}